home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Utilities / Programming / C Reference Card 2.3 / C Reference Card / C Reference Card.rsrc / TEXT_401_1.txt < prev    next >
Encoding:
Text File  |  1995-11-14  |  8.1 KB  |  191 lines

  1. BASICS : C versus C++, program form, data types, strings, constants ...
  2. _________________________________________________________________________
  3.  
  4.  
  5. C VERSUS C++
  6.  
  7. C is a subset of C++.  Any C program file should compile on a C++ compiler*.  If your wondering whether you should learn one or the other - don't.  They are "virtually" the same (pun intended).  However, most people would probably recommend learning C++ versus just C.  It's sort of like running a marathon only to stop just short of the finish line and say, "well, I've gone far enough".
  8.  
  9. As a note, every program in this reference has been compiled and run to verify syntax and assure that the code snippets are correct.
  10.  
  11.  
  12.  
  13. PROGRAM FORM
  14.  
  15. As an ongoing tradition, the first program you write should be the infamous "Hello World" program.
  16.  
  17.   // hello.cp
  18.   #include <iostream.h>
  19.  
  20.   void main( void )
  21.   {
  22.     cout << "hello world" << endl;
  23.   }
  24.   // end hello.cp
  25.  
  26. Anything on a line after a double slash (//) is ignored by the compiler and is the standard way of commenting code.  Another way to comment your code is to use the slash-asterisk method.  The following program "square.cp" is almost as simple as the one above, except it demonstrates the basics of using functions as well as both styles of comments.
  27.  
  28.   // square.cp
  29.   /*
  30.      Sometimes it convenient to use the "old" style comments, especially
  31.      when you have more than one line of stuff to say.
  32.   */
  33.  
  34.   #include <iostream.h> // standard library.
  35.  
  36.   #define MAX 10        // preprocessor directive.
  37.  
  38.   int DoSquare(int);    // function prototypes required in C++.
  39.  
  40.   void main( void )     // main is the start of all C programs.
  41.   {
  42.     int n;
  43.     for(n=1;n<MAX;n++)
  44.       cout << n << " squared = " << DoSquare(n) << endl;
  45.   }
  46.  
  47.   int DoSquare(int m)   // function definition.
  48.   {
  49.     m = m * m;
  50.     return m;           // return value.
  51.   }
  52.   // end square.cp
  53.  
  54. White space is ignored in C/C++.  Brackets {} are used to group (or enclose) multiple statements.  Function calls are depicted with parenthesis () at the end of a function name which enclose variables which are used during the function call.  Semicolons depict the end of a statement (i.e., you can place multiple statements on a single line separated by semicolons if you wanted).
  55.  
  56.  
  57.  
  58. DATA TYPES AND TYPE CONVERSION
  59.  
  60. The following program identifies the built-in data types supported by C and methods for converting between these data types.
  61.  
  62.   // types.cp
  63.   #include <iostream.h>
  64.  
  65.   void main( void )
  66.   {
  67.     // declarations
  68.     char                c = 'A';  // usually 1-byte long.
  69.     short int           si= 1;    // minimum range +/-32767.
  70.     short               s = 2;    // short same as short int.
  71.     int                 i = 3;    // minimum range +/-32767.
  72.     long int            li= 4;    // minimum range +/-2147483647.
  73.     long                l = 5;    // long same as long int.
  74.     float               f = 10.1; // min 6 digits (decimal) precision.
  75.     double              d = 11.2; // min 10 digits (decimal) precision.
  76.     long double         ld= 12.3;
  77.  
  78.     unsigned char       uc;       // unsigned integers can only store
  79.     unsigned short int  usi;      // positive numbers.
  80.     unsigned int        ui;
  81.     unsigned long int   uli;
  82.  
  83.     signed char         sc;       // signed integers can store positive
  84.     signed short int    ssi;      // or negative numbers.
  85.     signed int          si2;
  86.     signed long int     sli;
  87.  
  88.     // simple assignment
  89.     s = 3;
  90.     cout << s << endl;
  91.  
  92.     // automatic conversion
  93.     f = s * i / d;
  94.     cout << f << endl;
  95.  
  96.     // inline conversions
  97.     ld = (long double)i;
  98.     s = short(d);
  99.     cout << ld << endl << s << endl;
  100.   }
  101.   // end types.cp
  102.  
  103.  
  104.  
  105. STRINGS
  106.  
  107. Strings in C are "null terminated".  This means that the following declaration;
  108.  
  109.   char *str = "Test string";
  110.  
  111. allocates a block of memory 12 bytes long and returns a pointer 'str' to the first character in the string.  The first 11 bytes contain the characters "Test string", the 12th byte contains NULL (i.e., \0 or zero).  To declare an empty string, use the following:
  112.  
  113.   char *nullStr = "";
  114.  
  115. Since the MacOS is based on Pascal strings, it is important that the difference be discussed.  The same string in Pascal would also be 12 bytes long, however, the first character in the string is actually the integer '11' which defines how many characters are in the string.  Your compiler should provide functions such as CtoPstr() and PtoCstr() to convert between the two formats.  If you want to declare a Pascal-style string in C, use the following:
  116.  
  117.   char *Pstr = "\pThis is a Pascal string";
  118.  
  119.  
  120.  
  121. CONSTANTS
  122.  
  123.   // constant definition examples
  124.   #define INTEGER         123
  125.   #define LONG            123L
  126.   #define UNSIGNED_LONG   123UL
  127.   #define FLOAT           12.3F
  128.   #define CHAR_CONST      'A'
  129.   #define OCTAL           037           /* leading zero */
  130.   #define HEXADECIMAL     0X5
  131.   #define STRING          "characters"
  132.  
  133.   // escape sequences
  134.   #define ALERT           \a
  135.   #define BACKSPACE       \b
  136.   #define FORMFEED        \f
  137.   #define NEWLINE         \n
  138.   #define CARRIAGE_RETURN \r
  139.   #define HORIZ_TAB       \t
  140.   #define VERT_TAB        \v
  141.   #define BACKSLASH       \\
  142.   #define QUESTION_MARK   \?
  143.   #define SINGLE_QUOTE    \'
  144.   #define DOUBLE_QUOTE    \"
  145.   #define OCTAL_SEQ       \o13          /* vertical tab */
  146.   #define HEX_SEQ         \x7           /* alert */
  147.  
  148.   // enumeration constants
  149.   enum boolean { FALSE, TRUE };
  150.   enum identifiers { first = 1, second, third };
  151.  
  152. The first item in an enumeration statement has a value of 0, the next 1, the next 2, etc. unless specified values are provided.
  153.  
  154.  
  155.  
  156. TERMINOLOGY
  157.  
  158. There‚Äôs a lot of fancy terminology in C++ which tends to confuse the novice.  Here are some of the buzz words that are used in object-oriented programming and what they mean:
  159.  
  160. Instances - Variables of a pre-defined class type are called instances of that class, or objects.
  161.  
  162. Objects - Objects are variables which are instances of a class.  Here is a simple example:
  163.  
  164.   class Student          // define class Student
  165.   {
  166.     char *name;
  167.     char *address;
  168.     int  id;
  169.  
  170.     void input( void );  // class methods
  171.     void print( void );
  172.   }
  173.  
  174.   Student freshman;      // freshman is an object,
  175.                          // a class variable, and
  176.                          // an instance of the class Student. 
  177.  
  178. Methods - Methods are nothing more than member functions of a class.
  179.  
  180. Polymorphism - When the same function works on different types of objects, it‚Äôs called polymorphism.  For example, you OPEN a door, you OPEN a window, and you OPEN your eyes.  Polymorphism means ‚Äúmany different forms‚Äù.
  181.  
  182. Encapsulation - The combination of member data and member functions (or methods) into an object.  With C++, you assign an object data attributes and methods which operate on the data.  Generally speaking, all of the code for a particular class of objects is maintained in a separate source code file, or in other words, it‚Äôs encapsulated.
  183.  
  184. Inheritance - One of the coolest things about C++ is that you can create an object which inherits all of the capabilities of a parent object, and then make minor modifications to suit your needs.  For example, if there was a window class which did everything you needed except for, say, window resizing.  You could create a subclass of the window class and then add the code needed to perform the task.  There are two important things to realize: 1) you only need to add the code to perform the specific task you need, and; 2) you don‚Äôt need to original source code for the parent class to make modifications.
  185.  
  186. Multiple Inheritance - Inheriting capabilities or traits from more than one parent defines multiple inheritance.  There are some problems with using multiple inheritance and many programmers avoid it at all costs (similar to using goto statements), but there are times when it can be useful.
  187.  
  188. Virtual Function (or method) - Allows polymorphism by defining a function which is called by an object at runtime (i.e., late binding) instead of at compile time (i.e., early binding).
  189.  
  190. _________________________________________________________________________
  191. *  There are some minor things you need to worry about if your calling a function from a precompiled C object file within a C++ program.  Reference the section "Functions" for more information.